<template>
  <div>
    <el-container>
      <el-main>
        <el-col :xs="24">
          <el-card header="部门领导审批表">
            <el-container>
              <el-tag type="warning">截止日期: {{deadLine}} 号</el-tag>
              <el-aside style="float:right; text-align: right; width: 85%">
                <el-popover
                  placement="left"
                  width="600px"
                  trigger="click">
                  <el-table :key="pageKey" :data="materialNameDatas">
                    <el-table-column width="150" property="name" label="物料名称"></el-table-column>
                    <el-table-column width="200" property="specification" label="型号及规格"></el-table-column>
                    <el-table-column width="300" property="unit" label="单位"></el-table-column>
                    <el-table-column width="300" property="type" label="物料类型"></el-table-column>
                  </el-table>
                  <!-- 分页器 -->
                  <div class="block" style="margin-top: 15px;">
                    <el-pagination
                      :current-page="mcurrentPage"
                      :page-sizes="[5, 10, 20, 30]"
                      :page-size="pageSize"
                      layout="total, prev, pager, next"
                      :total="mtotal"
                      @size-change="handleSizeChange"
                      @current-change="handleCurrentChange">
                    </el-pagination>
                  </div>
                  <el-button slot="reference" @click="materialimfo()">查询物料信息表</el-button>
                </el-popover>
              </el-aside>
            </el-container>
          </el-card>
        </el-col>
        <el-col :xs="24">
          <el-card>
            <!--后端完成后 最后添加v-loading="loading" -->
            <el-table :key="itemKey" ref="multipleTable" :data="tableData" :fit="true" :show-header="true" v-loading="loading">
              <el-table-column type="selection"></el-table-column>
              <el-table-column prop="id" label="id" sortable="true" v-if="false"></el-table-column>
              <el-table-column prop="materialName" label="物料名称"></el-table-column>
              <el-table-column prop="specification" label="型号及规格"></el-table-column>
              <el-table-column prop="unit" label="单位"></el-table-column>
              <el-table-column prop="purchaseNum" label="采购数量"></el-table-column>
              <el-table-column prop="partUsed" label="使用部位"></el-table-column>
              <el-table-column prop="remark" label="备注"></el-table-column>
              <el-table-column prop="purchaseStatus" label="状态"></el-table-column>
              <el-table-column fixed="right" width="200px">
                <template slot="header" slot-scope="scope">
                  <el-button
                    size="mini"
                    type="primary"
                    @click="handleInsert(scope.$index,scope.row)">添 加</el-button>
                </template>
                <template slot-scope="scope">
                  <el-button
                    mc-type="column-el-button"
                    size="mini"
                    type="primary"
                    @click="handleEdit(scope.$index, scope.row)">编 辑</el-button>
                  <el-button mc-type="column-el-button" size="mini" type="danger" @click="handleDelete(scope.$index, scope.row)">删 除</el-button>
                </template>
              </el-table-column>
            </el-table>
            <el-pagination style="margin-left: -5px;" layout="prev,pager,next" :total="pageTotal" :current-page.sync="currentPage"></el-pagination>
            <el-button-group>
              <el-button id="uuid00cd079a-755c-442a-b271-d40912245531" @click="handleConfirmAll()" type="primary">审 批</el-button>
              <el-button id="uuid00cd079a-755c-442a-b271-d40912245532" @click="handleCancelAll()" type="warning">打 回</el-button>
            </el-button-group>
          </el-card>
        </el-col>
      </el-main>
    </el-container>
    <!--编辑修改信息弹窗-->
    <el-dialog title="修改信息" :visible.sync="editFormVisible" :before-close="handleEditClose" width="30%">
      <el-form class="action-form" :model="updForm" label-width="100px">
        <el-form-item label="物资名称">
          <el-input :placeholder="updForm.materialName" :disabled="true" />
        </el-form-item>
        <el-form-item label="采购数量">
          <el-input v-model="updForm.purchaseNum" />
        </el-form-item>
        <el-form-item label="使用部位">
          <el-input v-model="updForm.partUsed" />
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="updForm.remark" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="updFormCancel()">取 消</el-button>
        <el-button type="primary" @click="updFormConfirm()">确 定</el-button>
      </div>
    </el-dialog>
    <!--添加物料弹窗-->
    <el-dialog title="添加物料" :visible.sync="insFormVisible" :before-close="handleInsClose" width="40%">
      <el-form class="action-form" :model="insForm" label-width="100px">
        <el-form-item label="物资名称">
          <el-autocomplete
            v-model="insForm.materialName"
            :fetch-suggestions="querySearchAsync"
            placeholder="请输入内容"
            @select="handleSelect"
          ></el-autocomplete>
        </el-form-item>
        <el-form-item label="采购数量">
          <el-input v-model="insForm.purchaseNum" />
        </el-form-item>
        <el-form-item label="使用部位">
          <el-input v-model="insForm.partUsed" />
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="insForm.remark" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="insFormCancel()">取 消</el-button>
        <el-button type="primary" @click="insFormConfirm()">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>

import { getToken } from '@/utils/auth'
import {
  updateMaterial,
  deleteById,
  selAllMaterial,
  selDeadLine,
  selAccountDepart, selAllBaseInfo
} from '@/api/material-purchase/purchase-plan'
import { updStatusAll, insertPurchase, initTable } from '@/api/material-purchase/department-audit'

export default {
  data() {
    return {
      tableData: [],
      editFormVisible: false, // 编辑框是否可见
      insFormVisible: false, //  添加弹出框是否可见
      selFormVisible: false, //  查询物料框是否可见
      loading: true,
      mcurrentPage: 1, //  物料信息表当前页码
      mtotal: 0, //  初始化总条数
      pageSize: 10, //  物料信息表每页的数据条数
      pageTotal: 10, //  初始化总条数
      currentPage: 1, //  申请表当前页码
      pageKey: '', // 分页功能中 table 的key值
      itemKey: '', //  使用key属性强制替换元素，从而触发组件的生命周期钩子或者触发过渡
      materialNameDatas: [], // 记录所有根据名字搜索的内容信息
      materialBaseInfo: [], //  记录所有物料基本信息
      timeout: null, //  设置搜索时的响应时间
      deadLine: 0, //  截止日期
      account: this.$store.getters.name, // 获取用户信息
      acoDepartName: '', // 获取用户所属部门信息
      updForm: {
        id: '',
        materialName: '',
        purchaseNum: '',
        partUsed: '',
        remark: ''
      },
      insForm: {
        materialName: '',
        purchaseNum: '',
        partUsed: '',
        remark: ''
      },
      headers: {
        Authorization: getToken()
      }
    }
  },
  //  在模板渲染成html或者模板编译进路由前调用 created.即：通常初始化某些属性值，然后再渲染成视图
  created() {

    this.getDeadLine()
    this.getDepartName()
    //this.init()
    console.log('account: ' + this.account)
  },
  mounted() {
    this.getDepartName()
   // this.init()
    selAllMaterial(this.mcurrentPage, this.pageSize).then((response) => {
      this.materialNameDatas = response.data.allMaterials
      this.mtotal = response.data.total
      this.pageKey = Math.random()
    })
    selAllBaseInfo().then((response) => {
      // console.log('直接输出所有物料信息: ' + response.data)
      this.materialBaseInfo = response.data
    })
  },

  methods: {
    //  初始化界面
    init() {
      // initTable(this.acoDepartName, this.currentPage, this.pageSize).then((response) => {
      //   console.log(this.acoDepartName)
      //   this.tableData = response.data.allMaterials
      //   this.pageTotal = response.data.total
      //   this.loading = false
      //   this.itemKey = Math.random()
      // })
      // initTable('部门一', this.currentPage, this.pageSize).then((response) => {
      //   this.tableData = response.data.allMaterials
      //   this.pageTotal = response.data.total
      //   this.loading = false
      //   this.itemKey = Math.random()
      // })
    },
    //  获取截止日期
    getDeadLine() {
      selDeadLine().then((response) => {
        // console.log('截止日期：' + response)
        this.deadLine = response.data.deadline
      })
    },
    // 获取部门名称
    getDepartName() {
      selAccountDepart(this.account).then((response) => {
        this.acoDepartName = response.data.departName
        // console.log('部门信息：' + this.acoDepartName)
        initTable(this.acoDepartName, this.currentPage, this.pageSize).then((response) => {
          console.log(this.acoDepartName)
          this.tableData = response.data.allMaterials
          this.pageTotal = response.data.total
          this.loading = false
          this.itemKey = Math.random()
        })
      })
    },
    //  获取所有物资基本信息
    materialimfo() {
      selAllMaterial(this.mcurrentPage, this.pageSize).then((response) => {
        // console.log('数据: ' + response.data.allMaterials)
        this.materialNameDatas = response.data.allMaterials
        this.mtotal = response.data.total
        this.pageKey = Math.random()
      })
    },
    // 查询物料信息表 每页条数改变时触发 选择一页显示多少行
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`)
      this.mcurrentPage = 1
      this.mpageSize = val
      this.pageKey = Math.random()
    },
    // 初始化表 每页条数改变时触发 选择一页显示多少行
    handlePageSizeChange(val) {
      console.log(`每页 ${val} 条`)
      this.currentPage = 1
      this.pageSize = val
      this.itemKey = Math.random()
    },
    // 查询物料信息表 当前页改变时触发 跳转其他页
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`)
      this.mcurrentPage = val
      selAllMaterial(this.mcurrentPage, this.pageSize).then((response) => {
        // console.log('数据: ' + response.data.allMaterials[0].name)
        this.materialNameDatas = response.data.allMaterials
        this.mtotal = response.data.total
        this.pageKey = Math.random()
      }).catch(error => {
        console.log('请求失败')
        console.log(error)
      })
    },
    // 查询物资采购表 当前页改变时触发 跳转其他页
    handleCurChange(val) {
      console.log(`当前页: ${val}`)
      this.currentPage = val
      initTable(this.acoDepartName, this.currentPage, this.pageSize).then((response) => {
        // console.log('数据: ' + response.data.allMaterials[0].name)
        this.tableData = response.data.allMaterials
        this.pageTotal = response.data.total
        this.itemKey = Math.random()
      }).catch(error => {
        console.log('请求失败')
        console.log(error)
      })
    },
    //  实现实时搜索功能
    //  fetch-suggestions:返回输入建议的方法，仅当你的输入建议数据 resolve 时，通过调用 callback(data:[]) 来返回它
    querySearchAsync(queryString, callback) {
      // console.log('material1:' + this.materialNameDatas)
      var datas = this.materialBaseInfo
      var results = queryString ? datas.filter(this.createStateFilter(queryString)) : datas
      var result = []
      for (var i = 0; i < results.length; i++) {
        result.push({ 'value': results[i].materialName })
        // console.log('material2:' + result)
      }
      // console.log('material3:' + result)
      clearTimeout(this.timeout)
      this.timeout = setTimeout(() => {
        callback(result)
      }, 3000 * Math.random())
    },
    createStateFilter(queryString) {
      return (state) => {
        // console.log('state:' + state.name)
        return (state.materialName.toLowerCase().indexOf(queryString.toLowerCase()) > -1)
      }
    },
    handleSelect(item) {
      console.log(item)
    },
    //  关闭 编辑框 之前的操作
    handleEditClose() {
      this.editFormVisible = false
      this.updForm.materialName = ''
      this.updForm.purchaseNum = ''
      this.updForm.partUsed = ''
      this.updForm.remark = ''
    },
    // 关闭 编辑框 之前的操作
    updFormCancel() {
      this.editFormVisible = false
      this.updForm.materialName = ''
      this.updForm.purchaseNum = ''
      this.updForm.partUsed = ''
      this.updForm.remark = ''
    },
    //  关闭 添加窗口 之前的操作
    handleInsClose() {
      this.insFormVisible = false
      this.insForm.materialName = ''
      this.insForm.purchaseNum = ''
      this.insForm.partUsed = ''
      this.insForm.remark = ''
    },
    // 关闭 添加物料信息框 之前的操作
    insFormCancel() {
      this.insFormVisible = false
      this.insForm.materialName = ''
      this.insForm.purchaseNum = ''
      this.insForm.partUsed = ''
      this.insForm.remark = ''
    },
    //  之后可以加一个 判断物料是否在库中存在的条件
    insFormConfirm() {
      if (this.insForm.materialName === '' || this.insForm.purchaseNum === '') {
        this.$message.error('物料名称或采购数量信息不能为空！')
      } else {
        insertPurchase(this.insForm.materialName, this.insForm.purchaseNum, this.insForm.partUsed, this.insForm.remark, this.acoDepartName).then(response => {
          this.$message.success(response.message)
          this.insFormVisible = false
          this.loading = true
          this.init()
          this.insForm.materialName = ''
          this.insForm.purchaseNum = ''
          this.insForm.partUsed = ''
          this.insForm.remark = ''
        })
      }
    },
    //  添加物料
    handleInsert(index, row) {
      const newDate = new Date()
      if (newDate.getDate() > this.deadLine) {
        this.$message({
          showClose: true,
          message: '当前时间已过截至日期!',
          type: 'warning'
        })
        return
      }
      this.insFormVisible = true
    },
    //  编辑物料信息  可能需要 去掉等号后面的 this
    handleEdit(index, row) {
      // console.log('row: ' + row)
      this.editFormVisible = true
      this.updForm.index = index
      this.updForm.id = this.tableData[index].id
      this.updForm.materialName = this.tableData[index].materialName
      this.updForm.purchaseNum = this.tableData[index].purchaseNum
      this.updForm.partUsed = this.tableData[index].partUsed
      this.updForm.remark = this.tableData[index].remark
    },
    //  根据 id 删除物料   row：该行数据
    handleDelete(index, row) {
      this.$confirm('此操作将删除物料信息, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteById(this.tableData[index].id).then((response) => {
          this.$message.success(response.message)
          this.loading = true
          this.init()
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    //  编辑物料内容
    updFormConfirm() {
      this.editFormVisible = false
      updateMaterial(
        this.updForm.id,
        this.updForm.purchaseNum,
        this.updForm.partUsed,
        this.updForm.remark
      ).then((response) => {
        this.$message.success(response.message)
        this.loading = true
        this.init()
        this.updForm.departmentName = ''
        this.updForm.principal = ''
      }).catch((error) => {
        console.log(error)
      })
    },
    //  审批物料信息
    handleConfirmAll() {
      this.$confirm('确定审批选中的数据吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const newDate = new Date()
        if (newDate.getDate() > this.deadLine) {
          this.$message({
            showClose: true,
            message: '当前时间已过截至日期!',
            type: 'warning'
          })
          return
        }
        var RowDatas = this.$refs.multipleTable.selection
        console.log('输出选中值: ' + RowDatas)
        if (RowDatas.length < 1) {
          this.$message({
            showClose: true,
            message: '请至少选择一项内容',
            type: 'warning'
          })
          return
        }
        var RowIds = [] // 记录所选行的id
        var status = '审核中'
        //  获取 选中行 的id
        for (var i = 0; i < RowDatas.length; i++) {
          RowIds = RowIds + RowDatas[i].id
          if (i < RowDatas.length - 1) {
            RowIds += ','
          }
        }
        updStatusAll(RowIds, status).then((response) => {
          this.$message.success(response.message)
          this.loading = true
          this.init()
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消审批'
        })
      })
    },
    //  打回操作：修改物料状态为  计划中
    handleCancelAll() {
      this.$confirm('是否要打回选中的数据?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const newDate = new Date()
        if (newDate.getDate() > this.deadLine) {
          this.$message({
            showClose: true,
            message: '当前时间已过截至日期!',
            type: 'warning'
          })
          return
        }
        var RowDatas = this.$refs.multipleTable.selection
        console.log('输出选中值: ' + RowDatas)
        if (RowDatas.length < 1) {
          this.$message({
            showClose: true,
            message: '请至少选择一项内容',
            type: 'warning'
          })
          return
        }
        var RowIds = [] // 记录所选行的id
        var status = '计划中'
        //  获取 选中行 的id
        for (var i = 0; i < RowDatas.length; i++) {
          RowIds = RowIds + RowDatas[i].id
          if (i < RowDatas.length - 1) {
            RowIds += ','
          }
        }
        updStatusAll(RowIds, status).then((response) => {
          this.$message.success(response.message)
          this.loading = true
          this.init()
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消修改'
        })
      })
    }

  }
}
</script>

<style scoped>
</style>
